import { Button, Form, Input, Space, type FormItemProps } from 'antd';
import { type NamePath } from 'antd/es/form/interface';
import { ReactNode } from 'react';
import styles from './index.less';

export type QueryFormField = {
  label: ReactNode;
  name: NamePath;
  labelCol?: number;
  formItemProps: FormItemProps;
  children: ReactNode;
};
export interface QueryFormProps {
  fields: QueryFormField[];
  labelCol?: number;
  fieldWidth?: number;
  initialValues?: any;
  onSearch?: (values?: any) => void;
}
const QueryForm = (props: QueryFormProps) => {
  const {
    fields,
    labelCol = 8,
    onSearch,
    initialValues,
    fieldWidth = 300,
  } = props;
  const [form] = Form.useForm();
  const handleSearch = async () => {
    const values = await form.validateFields();
    onSearch?.(values);
  };
  const handleReset = () => {
    form.resetFields();
    onSearch?.(initialValues);
  };
  return (
    <Form
      form={form}
      labelAlign="left"
      labelCol={{ span: labelCol }}
      wrapperCol={{ span: 24 - labelCol }}
      initialValues={initialValues}
    >
      <div className={styles['query-form']}>
        {fields?.map((field) => (
          <div
            key={field.name}
            className={styles['query-form-item']}
            style={{ width: fieldWidth }}
          >
            <Form.Item
              label={field.label}
              name={field.name}
              {...field.formItemProps}
            >
              {field.children || <Input allowClear placeholder="请输入" />}
            </Form.Item>
          </div>
        ))}
        <Space>
          <Button type="primary" onClick={handleSearch}>
            查询
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </Space>
      </div>
    </Form>
  );
};

export default QueryForm;
